package com.cinsea.ext.vmeeting;
import com.cinsea.common.ActionType;
import com.cinsea.common.BasePX;
import com.cinsea.common.Env;
import com.cinsea.common.JdbcDao;
import com.cinsea.htmlselect.service.OptionService;
import com.cinsea.interfaces.model.Cell;
import com.cinsea.interfaces.model.Dataset;
import com.cinsea.interfaces.workflow.RequestInfo;
import com.cinsea.interfaces.workflow.WorkflowServiceImpl;
import com.cinsea.util.DateUtil;
import com.cinsea.util.StringUtil;
import com.cinsea.ext.vmeeting.model.Reservermeeting;
import com.cinsea.ext.vmeeting.model.Vmeeting;
import com.cinsea.ext.vmeeting.service.VmeetingService;
import org.apache.commons.httpclient.HttpClient;
import org.dom4j.Document;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: xuhuanchao
 * Date: 13-4-25
 * Time: 下午2:13
 * To change this template use File | Settings | File Templates.
 */
public class VmeetingPX extends BasePX {

    @Override
    public void before(Map map) {
        Vmeeting vmeeting ;
        Map<String,Object> meetingMap = new HashMap<String,Object>();
        Reservermeeting reservermeeting = new Reservermeeting();
        String processId = StringUtil.null2String(map.get("processid"));
        String actionType = map.get("actiontype")==null?"":map.get("actiontype").toString();
        JdbcDao jdbcDao =  Env.getBean("jdbcDao");
        String sql = "SELECT * FROM ut_vmeetingapply WHERE processid=?";
        if(actionType.equals("submit")){
            List meetingApplyInfos = jdbcDao.queryForList(sql,new Object[]{processId});
            if(meetingApplyInfos.size() > 0){
                Map row = (Map)meetingApplyInfos.get(0);
                reservermeeting.setTheme(row.get("zhuti").toString());
                String sTime =row.get("kaishiriqi").toString()+" "+row.get("kssj");
                String eTime =row.get("jieshuriqi").toString()+" "+row.get("jssj");
                meetingMap.put("stime",sTime);
                meetingMap.put("etime",eTime);
                reservermeeting.setStartTime(getGmtTime(sTime,0));
                reservermeeting.setEndTime(getGmtTime(eTime,0));
                int attendeeamount =4;
                reservermeeting.setPeopleNumber(attendeeamount);
                reservermeeting.setMeetingPwd(row.get("canhuimima").toString());
                reservermeeting.setMeetingModel("1");
                reservermeeting.setMeetingDescribe("");
                reservermeeting.setAttendee(StringUtil.null2String(row.get("canhuiren")));
                //创建会议
                vmeeting = createConference(reservermeeting,2);//fixed meeting
                if(vmeeting.getResult().equals("SUCCESS")){
                    jdbcDao.update("update ut_vmeetingapply set huiyiid=? where processid=?",new Object[]{vmeeting.getConfKey(),processId});
                    meetingMap.put("vmeeting",vmeeting);
                    meetingMap.put("reservermeeting",reservermeeting);
                    String processid = createNotification(meetingMap);//创建通知
                }
            }
        }
    }

    /**
     * 调用会议申请的服务,创建会议
     * @param param
     *
     */
    private Vmeeting createConference(Reservermeeting param,int meetingtype)    {
        Vmeeting vmeeting = new Vmeeting();
        if(param == null){
            return vmeeting;
        }
        VmeetingService vs = Env.getBean("vmeetingService");
        OptionService optionService =  Env.getBean("optionService");
        vs.setUrl(optionService.get("4028818e3e687c67013e688b8c480008").getObjdesc());
        vmeeting = vs.createReservemeeting(param,meetingtype);
        return vmeeting;
    }

    /**
     * 调用创建通知流程的API，将会议信息通知给参会人
     * @param meetingMap
     * @return
     */
    private String createNotification(Map<String,Object> meetingMap){
        OptionService optionService =  Env.getBean("optionService");
        String processId = "";
        WorkflowServiceImpl si = new WorkflowServiceImpl();
        RequestInfo formdata = new RequestInfo();
        formdata.setTypeid(optionService.get("4028818e3e687c67013e688bf8fb000b").getObjdesc());//通知流程ID
        formdata.setOperator(Env.getRemoteUser().getId());
        Dataset dataset = new Dataset();
        List<Cell> mainlist = new ArrayList(); //主表单元格
        String currentdate=DateUtil.getCurrentDate();
        Cell c1 = new Cell();
        c1.setId(optionService.get("4028818e3e687c67013e688c3cdd000c").getObjdesc());//title
        String titleVal = ((Reservermeeting)(meetingMap.get("reservermeeting"))).getTheme()+"会议于"+
                meetingMap.get("stime")+"开始";
        c1.setValue(titleVal);
        Cell c2 = new Cell();
        c2.setId(optionService.get("4028818f3e827132013e829377880006").getObjdesc());//留言发送人
        c2.setValue(Env.getRemoteUser().getId());
        Cell c3 = new Cell();
        c3.setId(optionService.get("4028818e3e687c67013e688d41a0000f").getObjdesc());//留言日期
        c3.setValue(currentdate);
        Cell c4 = new Cell();
        c4.setId(optionService.get("4028818e3e687c67013e688c9720000e").getObjdesc());//被留言人  || 接收人
        c4.setValue(((Reservermeeting)(meetingMap.get("reservermeeting"))).getAttendee());
        Cell c5 = new Cell();
        c5.setId(optionService.get("4028818e3e687c67013e688c63e1000d").getObjdesc());//留言内容
//        String meetingURL = optionService.get("4028818e3e687c67013e688b8c480008").getObjdesc()+"/meeting/app/attendeeJoin/index!validateConferencePassword.action?site=box&confId="+
//                    ((Vmeeting)(meetingMap.get("vmeeting"))).getConfId()+"&trainingPassword="+
//                    ((Reservermeeting)(meetingMap.get("reservermeeting"))).getMeetingPwd()+"&joinTime=" +
//
        String meetingActionURL = "/ext/com.cinsea.ext.vmeeting.VmeetingAction?action=sendnotify&site=box&confId="+
                                  ((Vmeeting)(meetingMap.get("vmeeting"))).getConfId()+"&trainingPassword="+
                                  ((Reservermeeting)(meetingMap.get("reservermeeting"))).getMeetingPwd()+"&joinTime="+
                                  ((Reservermeeting)(meetingMap.get("reservermeeting"))).getStartTime();
        VmeetingService vs = Env.getBean("vmeetingService");
        vs.setUrl(optionService.get("4028818e3e687c67013e688b8c480008").getObjdesc());
        String contentVal =  ((Reservermeeting)(meetingMap.get("reservermeeting"))).getTheme()+"会议将于"+
                meetingMap.get("stime")+"开始，"+"到"+
                meetingMap.get("etime")+"结束。"+
                             "<br>主持人密码为："+""+vs.getHostPassword(((Vmeeting)(meetingMap.get("vmeeting"))).getConfId())+
                             "<br>请准时参加会议。会议地址："+"<a href='"+meetingActionURL+"' target='_blank'>参加</a>";
        c5.setValue(contentVal);
        mainlist.add(c1);
        mainlist.add(c2);
        mainlist.add(c3);
        mainlist.add(c4);
        mainlist.add(c5);
        dataset.setMaintable(mainlist);
        formdata.setData(dataset);
        processId = si.createRequest(formdata);
        return processId;
    }

    public void after(Map map) {
        HttpClient httpClient = new HttpClient();
        String actiontype = (String) map.get("actiontype");
        String processId = (String) map.get("processid");
        JdbcDao jdbcDao =  Env.getBean("jdbcDao");
        String confKey="";
        Document document = null;
        if(actiontype.equals(ActionType.REJECT_WFPROCESS)){
            String sql="select huiyiid from ut_vmeetingapply where processid=?";
            List list = jdbcDao.queryForList(sql,new Object[]{processId});
            if(list.size() > 0){
                Map confId = (Map)list.get(0);
                confKey = confId.get("huiyiid").toString();
                VmeetingService vs = Env.getBean("vmeetingService");
                OptionService optionService =  Env.getBean("optionService");
                vs.setUrl(optionService.get("4028818e3e687c67013e688b8c480008").getObjdesc());
                vs.deleteVmeeting(confKey);
            }
        }

    }

    /**
     *根据时区进行时间转换，
     * @param s
     * @param tz
     * @return
     */
    private String getGmtTime(String s,int tz) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf1.setTimeZone(TimeZone.getTimeZone("GMT+" + tz));
        try {
            Date date = sdf.parse(s);
            String s1 = sdf1.format(date);
            String[] temp = s1.split(" ");
            s1 = temp[0]+"T"+temp[1];
            return s1;
        } catch (Exception e) {
            return s;
        }
    }



}
